package com.heima.controller;

import com.heima.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

//http://localhost:8080/consumer/8
@RestController
@RequestMapping("/consumer")
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallback")  //多个服务降级返回的方法
public class ConsumerController
{
    @Autowired
    private RestTemplate restTemplate;


    //获得配置信息，得到具体的微服务
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    //@HystrixCommand(fallbackMethod = "queryByIdFallback") //单个服务降级返回的方法
    @HystrixCommand
    //public User queryById(@PathVariable Long id)
    public String queryById(@PathVariable Long id)   //返回String类型错误信息
    {
        //eureka中只有一个服务时
        //String url="http://localhost:9091/user/"+id;

        //获取eureka中注册的user-service的所有实例
//        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = serviceInstances.get(0);
//
//        String url="http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+id;

        if(id==1)
        {
            throw new RuntimeException("太忙了！");
        }
        //负载均衡
//        String url="http://user-service/user/"+id;
//        User user= restTemplate.getForObject(url, User.class);
//        return user;

        //熔断器服务降级
        String url="http://user-service/user/"+id;
        return restTemplate.getForObject(url, String.class);

    }


//    public String queryByIdFallback(Long id)
//    {
//        log.error("查询失败",id);
//        return "网络太拥挤了";
//    }

    public String defaultFallback()
    {
        return "网络拥挤";
    }
}
